package cn.tedu.straw.portal.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDetailsServiceImpl userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 配置身份验证
        auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 访问控制
        // authorizeRequests()：对请求进行验证
        // antMatchers()：设置请求路径
        // permitAll()：直接许可，即不需要验证
        // anyRequest()：除了此前配置过的URL以外的所有请求
        // authenticated()：必须已经验证
        // formLogin()：通过登录表单来验证用户登录
        // csrf()：跨域攻击
        // disable()：禁止

        // 登录页面的URL
        String loginUrl = "/login.html";
        // 处理登录表单的URL
        String loginProcessingUrl = "/login";
        // 不需要登录即可请求的URL（白名单）
        String[] urls = {
                loginUrl,
                loginProcessingUrl,
                "/register.html",
                "/portal/user/register/student",
                "/browser_components/**",
                "/css/**",
                "/img/**",
                "/js/**",
                "/npm/**",
                "/favicon.ico",
                "/package-lock.json"
        };

        http.authorizeRequests()
                .antMatchers(urls).permitAll()
                .anyRequest().authenticated();

        http.formLogin()
                .loginPage(loginUrl)
                .loginProcessingUrl(loginProcessingUrl);

        http.csrf().disable();
    }

}
